package band.wukong.practice.javase.core.thread.timer;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Desc: 定时器
 * Author: sunjs
 * Date: 2009-11-5 15:44:56
 */
public class TestTimer extends Thread {
    private static int count;
    private int a;

    public void start() {
        super.start();
        Timer timer = new Timer(true);  //把与Timer关联的线程设为后台线程

        TimerTask task = new TimerTask() {
            public void run() {
                while (true) {
                    reset();
                    try {
                        sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };

        timer.schedule(task, 0, 5);  //设置定时任务(任务，延迟时间，周期)
    }

    public void reset() {
        a = 0;
    }

    public void run() {
        while (true) {
            System.out.println(getName() + ": " + a++);
            if (count++ == 100) break;
            yield();
        }
    }

    public static void main(String[] args) {
        TestTimer m = new TestTimer();
        m.start();
    }
}
